import { getToken } from '@/utils/storage.js'

export default (to, from, next, store, router) => {
  document.title = to.meta.name || document.title
  const token = getToken()
  if (!!token && to.path !== '/login') {
    store.commit('SET_TOKEN', token)
    if (store.getters.routerMap.length > 0) {
      next()
    } else {
      store
        .dispatch('getUserInfoActions')
        .then(() => {
          router.addRoutes(store.getters.routerMap)
          next({
            ...to,
            replace: true
          })
        })
        .catch(() => {
          next('/login')
        })
    }
  } else {
    if (to.path == '/login') {
      next()
    } else {
      next('/login')
    }
  }
}
